package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.entity.SysUserPostDo;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.service.ISysUserPostService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户与岗位关联Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-27
 */
@RequiredArgsConstructor
@Service
public class SysUserPostServiceImpl implements ISysUserPostService {
    private final SysUserPostMapper sysUserPostMapper;

    /**
     * 查询用户与岗位关联
     */
    @Override
    public SysUserPostDo queryById(Long userId) {
        return sysUserPostMapper.selectById(userId);
    }

    /**
     * 查询用户与岗位关联列表
     */
    @Override
    public TableDataInfo<SysUserPostDo> queryPageList(SysUserPostDo entity, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserPostDo> lqw = buildQueryWrapper(entity);
        Page<SysUserPostDo> result = sysUserPostMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户与岗位关联列表
     */
    @Override
    public List<SysUserPostDo> queryList(SysUserPostDo entity) {
        LambdaQueryWrapper<SysUserPostDo> lqw = buildQueryWrapper(entity);
        return sysUserPostMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<SysUserPostDo> buildQueryWrapper(SysUserPostDo entity) {
        Map<String, Object> params = entity.getParams();
        LambdaQueryWrapper<SysUserPostDo> lqw = Wrappers.lambdaQuery();
        return lqw;
    }

    /**
     * 新增用户与岗位关联
     */
    @Override
    public Boolean insert(SysUserPostDo entity) {
        SysUserPostDo add = BeanUtil.toBean(entity, SysUserPostDo.class);
        validEntityBeforeSave(add);
        Boolean flag = sysUserPostMapper.insert(add) > 0;
        if (flag) {
            entity.setUserId(add.getUserId());
        }
        return flag;
    }

    /**
     * 修改用户与岗位关联
     */
    @Override
    public Boolean updateById(SysUserPostDo entity) {
        SysUserPostDo update = BeanUtil.toBean(entity, SysUserPostDo.class);
        validEntityBeforeSave(update);
        return sysUserPostMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserPostDo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户与岗位关联
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return sysUserPostMapper.deleteBatchIds(ids) > 0;
    }
}
